package javaTest03.exercise02;

import java.sql.*;
import java.util.ResourceBundle;

public class JdbcUtils {

    static {//加载数据库驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }



    private JdbcUtils(){}

    public static Connection getConnection(String path) throws SQLException {//连接数据库
        ResourceBundle bundle=ResourceBundle.getBundle(path);
        String url=bundle.getString("url");//数据库地址
        String user=bundle.getString("user");//数据库账号
        String password=bundle.getString("password");//数据库密码
        return DriverManager.getConnection(url, user, password);
    }

    public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet){//关闭数据库连接

        if(resultSet!=null)
        {
            try {
                resultSet.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }

        if(statement!=null)
        {
            try {
                statement.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }

        if(connection!=null)
        {
            try {
                connection.close();
            } catch (SQLException throwable) {
                throwable.printStackTrace();
            }
        }
    }
}
